//
//  JDAddressListViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/6/17.
//

import UIKit
// 收货信息
class JDAddressListViewController: JDBaseViewController {

    var mainTableView: UITableView?
    var dataSource: [JDAddressModel?]?
    var changeReceiveAddress: ((JDAddressModel)->Void)?
    
    var isSelectedAddress: Bool = false
    var selectedIndex: Int = -1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupLeftBackItem()
        self.setupNavigationTitle("收货信息")
//        if isSelectedAddress {
//            self.customTextRightBarButtonItem("确定", #selector(rightBarButtonItemAction), self)
//        } else {
//            self.customTextRightBarButtonItem("新增", #selector(rightBarButtonItemAction), self)
//        }
        self.customTextRightBarButtonItem("新增", #selector(rightBarButtonItemAction), self)
    }
    
    @objc func rightBarButtonItemAction() {
        printLog("新增")
//        if isSelectedAddress {
//            
//            if self.selectedIndex != -1 {
//                if let selectedModel = self.dataSource?[self.selectedIndex] {
//                    self.changeReceiveAddress?(selectedModel)
//                }
//            }
//            self.navigationController?.popViewController(animated: true)
//
//        } else {
            let newAddressVC = JDAddAddressViewController()
//        self.addressChangeCallback?(false)
            newAddressVC.addressChangeCallback = { [weak self] state in
                if state {
                    self?.getNetData(true)
                }
            }
            self.hidesBottomBarPushViewController(newAddressVC)
//        }
    
    }
    
    func setupUIElements() {
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
        })
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.backgroundColor = .commonColor()
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
    }

    override func getNetData(_ isRefresh: Bool = true) {
        self.showLoading()
        JDNetWorkRequest(.getAddressList([:])) { responseStr in
        
            self.dismissLoading()
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                
                printLog("接口地址列表:\(responseStr)")
                if let addressModels = [JDAddressModel].deserialize(from: responseStr, designatedPath: "data") {
                    
                    if isRefresh {
                        // 刷新
                        self.dataSource = addressModels
                    } else {
                        // 加载
                        self.dataSource?.append(contentsOf: addressModels)
                    }
                    if addressModels.count < 10 {
                        self.mainTableView?.noMoreData()
                    }
                } else {
                    self.mainTableView?.noMoreData()
                }
                
            } else if commonModel?.code == "401" {
                // 未登录
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } failure: { error in
            self.mainTableView?.reloadData()
            self.mainTableView?.noMoreData()
            
            
        } error: { errorCode in
            self.mainTableView?.reloadData()
            self.mainTableView?.noMoreData()
        }

    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDAddressListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
        cell?.selectionStyle = .none
        
        for subV in cell?.contentView.subviews ?? [UIView]() {
            subV.removeFromSuperview()
        }
        cell?.contentView.backgroundColor = .commonColor()
        
        let addressModel = self.dataSource?[indexPath.row]
        
        let containerView = UIView()
        cell?.contentView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.left.equalTo(cell!.contentView).offset(12)
            make.right.equalTo(cell!.contentView).offset(-12)
            make.top.equalTo(cell!.contentView)
            make.bottom.equalTo(cell!.contentView).offset(-10)
        }
        containerView.layer.cornerRadius = 6
        containerView.backgroundColor = .white
        
        let markImgV = UIImageView()
        containerView.addSubview(markImgV)
        markImgV.snp.makeConstraints { make in
            make.right.top.equalTo(containerView)
            make.size.equalTo(CGSizeMake(16, 16))
        }
        markImgV.image = UIImage(named: "address_selected")?.withRenderingMode(.alwaysOriginal)
        markImgV.isHidden = true
        if self.selectedIndex == indexPath.row {
            // 选中的
            markImgV.isHidden = false
        } else {
            // 未选中
            markImgV.isHidden = true
        }
        
        let nameLabel = UILabel()
        containerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(containerView).offset(12)
            make.top.equalTo(containerView).offset(16)
            make.height.equalTo(25)
        }
        nameLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 18, weight: .semibold), textColor: color("#333333"))
        nameLabel.text = addressModel?.receiverName
        
        let phoneNumberLabel = UILabel()
        containerView.addSubview(phoneNumberLabel)
        phoneNumberLabel.snp.makeConstraints { make in
            make.left.equalTo(nameLabel.snp.right).offset(18)
            make.centerY.equalTo(nameLabel)
        }
        phoneNumberLabel.text = addressModel?.mobile
        phoneNumberLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"))
        
        let defaultLabel = JDPaddingLabel()
        containerView.addSubview(defaultLabel)
        defaultLabel.snp.makeConstraints { make in
            make.centerY.equalTo(phoneNumberLabel)
            make.left.equalTo(phoneNumberLabel.snp.right).offset(3)
        }
        defaultLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 10, weight: .regular), textColor: color("#F2460B"))
        defaultLabel.edgeInsets = UIEdgeInsets(top: 3, left: 5, bottom: 1, right: 5)
        defaultLabel.makeBorder(color("#FF3E2F"), 0.5)
        defaultLabel.text = "默认"
        defaultLabel.makeCorner(2)
        
        if addressModel?.defaultFlag == 1 {
            defaultLabel.isHidden = false
        } else {
            defaultLabel.isHidden = true
        }
        
        let addressInfoLabel = UILabel()
        containerView.addSubview(addressInfoLabel)
        addressInfoLabel.snp.makeConstraints { make in
            make.left.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(6)
            make.height.greaterThanOrEqualTo(20)
            make.right.equalTo(containerView).offset(-12)
        }
        addressInfoLabel.text = String.init(format: "%@%@%@%@", addressModel?.province ?? "", addressModel?.city ?? "", addressModel?.district ?? "", addressModel?.address ?? "" )//"辽宁省大连市甘井子区高云路136号2-1"
        addressInfoLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"))
        
        let line = UIView()
        containerView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(containerView).offset(12)
            make.right.equalTo(containerView).offset(-12)
            make.top.equalTo(addressInfoLabel.snp.bottom).offset(16)
            make.bottom.equalTo(containerView).offset(-54)
            make.height.equalTo(1)
        }
        line.backgroundColor = color("#F5F6F8")
        
        
        let middelLine = UIView()
        containerView.addSubview(middelLine)
        middelLine.snp.makeConstraints { make in
            make.centerX.equalTo(line)
            make.top.equalTo(line.snp.bottom).offset(18)
            make.bottom.equalTo(containerView).offset(-16)
            make.width.equalTo(1)
        }
        middelLine.backgroundColor = color("#F5F6F8")
        
        
        
        let deleteButton = UIButton(type: .custom)
        containerView.addSubview(deleteButton)
        deleteButton.snp.makeConstraints { make in
            make.left.equalTo(line)
            make.top.equalTo(line.snp.bottom)
            make.bottom.equalTo(containerView)
            make.right.equalTo(containerView.snp.centerX)
        }
        
        deleteButton.setTitle("删除", for: .normal)
        deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        deleteButton.setTitleColor(color("#8D9198"), for: .normal)
        deleteButton.tag = indexPath.row
        deleteButton.addTarget(self, action: #selector(deleteAddressAction(_:)), for: .touchUpInside)
        
        let editButton = UIButton(type: .custom)
        containerView.addSubview(editButton)
        editButton.snp.makeConstraints { make in
            make.right.equalTo(line)
            make.top.equalTo(line.snp.bottom)
            make.bottom.equalTo(containerView)
            make.left.equalTo(containerView.snp.centerX)
        }
        
        editButton.setTitle("编辑", for: .normal)
        editButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        editButton.setTitleColor(color("#FA6161"), for: .normal)
        editButton.addTarget(self, action: #selector(editAddressAction(_:)), for: .touchUpInside)
        editButton.tag = indexPath.row
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}

extension JDAddressListViewController {
    
    @objc func deleteAddressAction(_ button: UIButton) {
        
        self.showConfirmView("确定删除此地址吗？") { [weak self] in
            self?.deleteAddressRequest(index: button.tag)
        }
        
    }
    
    
    @objc func deleteAddressRequest(index: Int) {
        
        let selectedModel = self.dataSource?[index]
        
        var params = [String: Any]()
        params["id"] = selectedModel?.id
        self.showLoading()
        JDNetWorkRequest(.deleteAddress(params)) { responseStr in
            
            self.dismissLoading()
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                self.view.toast(message: "删除成功")
                self.getNetData(true)
            } else if commonModel?.code == "401" {
                // 未登录
            }
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    @objc func editAddressAction(_ button: UIButton) {
        
        let selectedAddressModel = self.dataSource?[button.tag]
        
        printLog("编辑~~~点击:\(button.tag)")
        
        let editAddressVC = JDAddAddressViewController()
        editAddressVC.addressModel = selectedAddressModel
        editAddressVC.type = 1
        editAddressVC.addressChangeCallback = { [weak self] state in
            if state {
                self?.getNetData(true)
            }
        }
        self.hidesBottomBarPushViewController(editAddressVC)
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        self.selectedIndex = indexPath.row
        if isSelectedAddress {
            // 结算页面过来的
            if self.selectedIndex != -1 {
                if let selectedModel = self.dataSource?[self.selectedIndex] {
                    self.changeReceiveAddress?(selectedModel)
                }
            }
            self.navigationController?.popViewController(animated: true)
            
        } else {
            self.mainTableView?.reloadData()
        }
    }
    
}
